package com.shengyuan.manage_os.old.ying.boce.jsy;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
//import org.ksoap2.serialization.SoapObject;
//import org.ksoap2.serialization.SoapPrimitive;

import android.content.pm.PackageManager.NameNotFoundException;
import android.util.Log;

import com.shengyuan.manage_os.old.ying.boce.http.FormFile;
import com.shengyuan.manage_os.old.ying.boce.http.HttpClient;
import com.shengyuan.manage_os.old.ying.boce.http.HttpException;
import com.shengyuan.manage_os.old.ying.boce.http.Response;
import com.shengyuan.manage_os.old.ying.boce.http.SocketHttpRequester;
import com.shengyuan.manage_os.old.ying.erpm.MainApplication;
import com.shengyuan.manage_os.old.ying.erpm.controls.CurrentTime;
import com.shengyuan.manage_os.old.ying.erpm.db.CLS_Actual_Data_Table;

public class APIErpm extends ApiSupport implements java.io.Serializable {
	public static final String TAG = "Weibo_API";
	public static String baseURL = Configuration.getScheme() + "erp.jiangshengyuan.com/";//  "192.168.0.8:3955/";//
	public static final String APP_SOURCE = Configuration.getSource();
	public String resid, message,strDt;
	private SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z", Locale.US);	
	public APIErpm() {
		super(); // In case that the user is not logged in
		format.setTimeZone(TimeZone.getTimeZone("GMT"));
	}

	public APIErpm(String userId, String password) {
		super(userId, password);
		format.setTimeZone(TimeZone.getTimeZone("GMT"));
	}

	public APIErpm(String userId, String password, String baseURL) {
		this(userId, password);
		this.baseURL = baseURL;
	}	
	
	public void reset() {
		http.reset();
	}

	public JSONObject Service_Save_ApplicationData(CLS_Actual_Data_Table cls)throws HttpException, JSONException	
	{
		ArrayList<BasicNameValuePair> arrayList = new ArrayList<BasicNameValuePair>();
		BasicNameValuePair params ;
		params = new BasicNameValuePair("Id", cls.Id+"");
		arrayList.add(params);
		params = new BasicNameValuePair("JSON1", cls.JSON1);
		arrayList.add(params);
		params = new BasicNameValuePair("JSON2", cls.JSON2 );
		arrayList.add(params);		
		params = new BasicNameValuePair("OVERTIME", cls.OVERTIME);
		arrayList.add(params);	
		params = new BasicNameValuePair("FINISHED", cls.FINISHED+"");
		arrayList.add(params);				
		params = new BasicNameValuePair("SENDED", cls.SENDED + "");
		arrayList.add(params);	
		params = new BasicNameValuePair("PRINTEABLED", cls.PRINTEABLED +"" );
		arrayList.add(params);
		params = new BasicNameValuePair("PCOUNT", cls.PCOUNT +"");
		arrayList.add(params);		
		params = new BasicNameValuePair("SERVICEID", cls.SERVICEID +"");
		arrayList.add(params);	
		
		Response response = post(getBaseURL(), arrayList, false, "Save_applicationdata");
		return response.asJSONObject();
	}
	public boolean UpLoadAllFilesAndData(CLS_Actual_Data_Table cls) {
		boolean ret = false;
		FormFile[] files = null;
	        try {
	            String requestUrl = getBaseURL();
	            Map<String, String> params = new HashMap<String, String>();
	            params.put("action", "upload");
	            params.put("Id", cls.Id+"");
	            params.put("USER", cls.USER);
	            params.put("FORM_TYPE", cls.FORM_TYPE);
//				params.put("FORM_TYPE", "com.ying.erpm.Actual_OA_DaKa_JiDong");
	            params.put("JSON1", cls.JSON1);
	            params.put("JSON2", cls.JSON2 );
	            params.put("OVERTIME", cls.OVERTIME);
	            params.put("FINISHED", cls.FINISHED+"");
	            params.put("SENDED", cls.SENDED + "");
	            params.put("PRINTEABLED", cls.PRINTEABLED +"" );
	            params.put("PCOUNT", cls.PCOUNT +"");
	            params.put("SERVICEID", cls.SERVICEID +"");
	            if (cls.mFilesLists!=null && cls.mFilesLists.length>0) {
	            	files = new FormFile[]{cls.mFilesLists[0]};
				}
	            ret = SocketHttpRequester.post(requestUrl, params, files);
				System.out.println("##########SocketHttpRequester.post========="+requestUrl+"@@"+params.toString()+"$$$$$"+files.length+"++++++"+ret);
	        } catch (Exception e) {
				System.out.println("##########SocketHttpRequester.Exception========="+e.toString());
	            e.printStackTrace();
	        }
	        return ret;
	}
	
	
	public JSONArray Service_Get_ApplicationData(String typename, String typecode, String method)throws HttpException, JSONException
	{
		JSONArray array = null;
		ArrayList<BasicNameValuePair> arrayList = new ArrayList<BasicNameValuePair>();
		BasicNameValuePair params ;
		if (typecode!=null) {
			params = new BasicNameValuePair("typecode", typecode);
			arrayList.add(params);
		}
		if (typename!=null) {
			params = new BasicNameValuePair("typename", typename);
			arrayList.add(params);
		}
		Response response = post(getBaseURL(), arrayList, false, method);
		JSONObject json = response.asJSONObject();
		System.out.println("##########AAAAAAAAAAAAAAA=========="+json.toString());
		if (json.getString("ret") == "true"){
			strDt =  json.getString("strDt");
			message = json.getString("message");
			array = new JSONArray(strDt) ;
		}else{
			//Toast.makeText((BoceApplication.mContext), json.getString("message"), Toast.LENGTH_LONG).show();
		}
		return array;
	}
	
	public JSONArray Service_Get_ApplicationData(String typename, String typecode)throws HttpException, JSONException
	{
		return Service_Get_ApplicationData(typename, typecode, "get_data");
	}

	public PT_yhmc login(String username, String password) throws  HttpException {
		
		Log.d(TAG, "Login attempt for " + username);
		ArrayList<BasicNameValuePair> arrayList = new ArrayList<BasicNameValuePair>();
		BasicNameValuePair params ;
		params = new BasicNameValuePair("txtUserName", username);
		arrayList.add(params);
		params = new BasicNameValuePair("txtPassword", password);
		arrayList.add(params);
		
		Response response = post(getBaseURL(), arrayList, false, "user_login");
		JSONObject json = response.asJSONObject();
		PT_yhmc user = new PT_yhmc();
		try {
			user.UserName = json.getString("UserName");
			user.ID = json.getInt("ID");
			user.JiaoSe = json.getString("JiaoSe");
			user.Department = json.getString("Department");
		} catch (Exception e) {
			// TODO: handle exception
		}
		return user;
	}
	
	public JSONArray GetContactList() throws  HttpException {	
		ArrayList<BasicNameValuePair> arrayList = new ArrayList<BasicNameValuePair>();
		Response response = post(getBaseURL(), arrayList, false, "user_contactlist");
		JSONArray json = response.asJSONArray();
		return json;
	}
	
	public JSONArray GetContactListTag() throws HttpException{
		ArrayList<BasicNameValuePair> arrayList = new ArrayList<BasicNameValuePair>();
		Response response = post(getBaseURL(), arrayList, false, "user_contactlisttag");
		JSONArray json = response.asJSONArray();
		return json;
	}
	
	public static String getBaseURL() {
		//return this.baseURL +  "PadOA/PadHandler.ashx"; //后台API执行接口
		return baseURL +  "PadOA/PadHandler.ashx"; //后台API执行接口
	}
	
	public static String GetMobileAndroid( String  Username, String Password) {
		String vs="";
		try {
			int v = MainApplication.Instance.getPackageManager()
					.getPackageInfo( MainApplication.Instance.getPackageName(), 0).versionCode;
			vs = v +"";
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return baseURL +  "MobileAndroid/MobileIndex.aspx" + "?V="+ vs +"&t="+ 
		CurrentTime.getTime().toString() +"&TxtUserName=" + 
		android.net.Uri.encode(Username)+"&TxtUserPwd=" +android.net.Uri.encode(Password); //工作管理WEB地址
	}
	
	public String getUpdateXml(){//升级文件
		return this.baseURL + "UploadFile/update.xml";
	}
	protected Response post(String url, ArrayList<BasicNameValuePair> params,
			boolean authenticated, String action) throws HttpException {
		if (url.indexOf("?") == -1) {
			url += "?source=" + APP_SOURCE;
		} else if (url.indexOf("source") == -1) {
			url += "&source=" + APP_SOURCE;
		}

		// 以HTML格式获得数据，以便进一步处理
		url += "&format=html&action=" + action;

		if (null != params && params.size() > 0) {
			url += "&" + HttpClient.encodeParameters(params);
		}
		return http.post(url, params);
	}	
	
	public boolean UpLoadFiles(File imageFile, int MdResID) {
		boolean ret = false;
	     Log.i(TAG, "upload start");
	        try {
	            String requestUrl = getBaseURL();
	            //请求普通信息
	            Map<String, String> params = new HashMap<String, String>();
	            params.put("action", "upload");
	            params.put("mdresid", MdResID+"");
	            params.put("fileName", imageFile.getName());
	            
	            //上传文件
	            if(  imageFile.getName().endsWith(".jpg")){
	            	FormFile formfile = new FormFile(imageFile.getName(), imageFile, "image", "application/octet-stream");
	            	SocketHttpRequester.post(requestUrl, params, formfile);
	            }
	            if( imageFile.getName().endsWith(".amr") ){
	            	FormFile formfile2 = new FormFile(imageFile.getName(), imageFile, "voice", "audio/amr");
	            	SocketHttpRequester.post(requestUrl, params, formfile2);
	            }

	            //SocketHttpRequester.uploadFile(imageFile.getAbsolutePath(), getBaseURL());
	            Log.i(TAG, "upload success");
	            ret = true;
	        } catch (Exception e) {
	            Log.i(TAG, "upload error");
	            e.printStackTrace();
	        }
	        Log.i(TAG, "upload end");
	        return ret;
	}
}
